package com.cf.base.leak.androidx;

import android.app.Activity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

/**
 * @author yangji
 */
public class FragmentXLeak extends FragmentManager.FragmentLifecycleCallbacks {

    private FragmentXCallback mCallback;

    public FragmentXLeak(FragmentXCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void onFragmentViewDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {
        View view = f.getView();
        if (view != null) {
            mCallback.leakage(view);
        }
    }

    @Override
    public void onFragmentDestroyed(@NonNull FragmentManager fm, @NonNull Fragment f) {
        super.onFragmentDestroyed(fm, f);
        mCallback.leakage(f);
    }

    public void invoke(Activity activity) {
        if (activity instanceof FragmentActivity) {
            ((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(this, true);
        }
    }
}
